package com.fhminyi.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class FileDownloadUtil {
    public static void downloadImage(String imageLocation, String savePath) throws IOException {
        BufferedImage img = null;
        try {
            // 尝试从URL加载图像
            if (imageLocation.toLowerCase().startsWith("http")) {
                img = ImageIO.read(new URL(imageLocation));
            } else {
                // 否则假设是本地文件路径
                img = ImageIO.read(new File(imageLocation));
            }
        } catch (IOException e) {
            throw new IOException("无法加载图像: " + e.getMessage(), e);
        }

        if (img == null) {
            throw new IOException("图像为空");
        }

        // 确保目标目录存在
        File saveDir = new File(savePath).getParentFile();
        if (saveDir != null && !saveDir.exists()) {
            saveDir.mkdirs();
        }

        // 获取文件扩展名
        String extension = getExtension(savePath);

        // 保存图像
        try {
            ImageIO.write(img, extension, new File(savePath));
        } catch (IOException e) {
            throw new IOException("无法保存图像: " + e.getMessage(), e);
        }
    }

    private static String getExtension(String filePath) {
        int lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == filePath.length() - 1) {
            return "jpg"; // 默认为jpg格式
        }
        return filePath.substring(lastDotIndex + 1).toLowerCase();
    }
}
